package com.gjt.serverSocket;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.*;

/**
 * Created with Intel IDEA.
 *  线程池 的Daytime 服务器
 * @Auther: gjt
 * @Date: 2024/5/5 10:03
 */
public class PooledDaytimeServer {
    private final static int PORT = 13;

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(50);
        try(ServerSocket server = new ServerSocket(PORT)){
            while (true){
                try{
                    Socket accept = server.accept();
                    Callable<String> daytimeTask = new DaytimeTask(accept);
                    Future<String> submit = executorService.submit(daytimeTask);
                    System.out.println(submit.get() + "已经执行完");
                }catch (IOException e){
                    e.printStackTrace();
                } catch (ExecutionException | InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }
    private static class DaytimeTask implements Callable<String>{
        private final Socket socket;

        public DaytimeTask(Socket socket) {
            this.socket = socket;
        }

        @Override
        public String call() throws Exception {
            try{
                BufferedWriter buf = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String now = simpleDateFormat.format(new Date());
                buf.write(now + "\r\n");
                buf.flush();
            }catch (IOException e){
                e.printStackTrace();
            } finally {
                try{
                    socket.close();
                }catch (IOException ignored){}
            }
            return Thread.currentThread().getName();
        }
    }
}
